package com.js.data.common.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.js.data.common.exception.ApiException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * easyExcel工具类
 */
public class ExcelUtil {


    public static List readExcel(MultipartFile excel, int sheetNo, Class cl) throws IOException {
        ExcelListener excelListener = new ExcelListener();
        return readExcel(excel, sheetNo, cl, excelListener);
    }

    public static List readExcel(MultipartFile excel, int sheetNo, Class cl, ExcelListener listener) throws IOException {
        String fileName = excel.getOriginalFilename();
        if (fileName == null || !(fileName.toLowerCase().endsWith(".xls") || fileName.toLowerCase().endsWith(".xlsx") || fileName.toLowerCase().endsWith(".xlsm"))) {
            throw new ApiException("导入失败,文件格式不正确！");
        }
        EasyExcel.read(excel.getInputStream(), cl, listener).sheet(sheetNo).doRead();
        return listener.getDatas();
    }


    /**
     * 导出Excel(07版.xlsx)到web
     *
     * @param response  响应
     * @param excelName Excel名称
     * @param sheetName sheet页名称
     * @param clazz     Excel要转换的类型
     * @param data      要导出的数据
     * @throws Exception
     */
    public static void export2Web(HttpServletResponse response, String excelName, String sheetName, Class clazz, List data) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        excelName = URLEncoder.encode(excelName, String.valueOf(StandardCharsets.UTF_8));
        response.setHeader("Content-disposition", "attachment;filename=" + excelName + ExcelTypeEnum.XLSX.getValue());
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }

}
